package storage

import (
	"fmt"
	"github.com/ZR233/gconfig"
	"gorm.io/driver/postgres"
	_ "gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
)

type GormPG struct {
	cfg       *gconfig.SqlCluster
	db        *gorm.DB
	configKey string
	DBName    string
}

func (g *GormPG) Open() (err error) {
	if g.cfg == nil {
		err = fmt.Errorf("pg config not init")
		return
	}
	cfg := g.cfg.Write
	if g.DBName != "" && cfg.DBName == "" {
		cfg.DBName = g.DBName
	}
	mainDsn := fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s",
		cfg.Host, cfg.Port, cfg.User, cfg.DBName, cfg.Password)

	g.db, err = gorm.Open(postgres.Open(mainDsn), &gorm.Config{})
	if err != nil {
		return
	}

	var replicas []gorm.Dialector

	for _, cfg = range g.cfg.Read {
		if g.DBName != "" && cfg.DBName == "" {
			cfg.DBName = g.DBName
		}
		dsn := fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s",
			cfg.Host, cfg.Port, cfg.User, cfg.DBName, cfg.Password)

		replicas = append(replicas, postgres.Open(dsn))
	}
	err = g.db.Use(dbresolver.Register(dbresolver.Config{
		Sources:  []gorm.Dialector{postgres.Open(mainDsn)},
		Replicas: replicas,
		// sources/replicas load balancing policy
		Policy: dbresolver.RandomPolicy{},
	}))

	return
}

func (g *GormPG) Close() (err error) {
	panic("implement me")
}

func (g *GormPG) GetConfigPtr() interface{} {
	panic("implement me")
}
